﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.IO;
using System.Text;
using System.Configuration;
using System.Text.RegularExpressions;

using Hangjing.Model;
using Hangjing.DBUtility;
using System.Data;
using System.Data.SqlClient;
using Hangjing.SQLServerDAL;
using Hangjing.Common;
using System.Threading.Tasks;

namespace Hangjing.WebCommon
{
    /// <summary>
    ///HJSendMsg 的摘要说明
    /// </summary>
    public class SendMsg
    {
        /// <summary>
        ///  发送短信
        /// </summary>
        /// <param name="mobile"></param>
        /// <param name="cont"></param>
        /// <returns>1表示成功，0表示失败</returns>
        public static int send(string mobile, string content)
        {
            return send(mobile, content, 1);
        }

        /// <summary>
        /// 配送员 完成配送 短信
        /// </summary>
        /// <param name="order"></param>
        /// <param name="deliver"></param>
        /// <returns></returns>
        public static int SendOrderComplete(string tel, string delivertel, string shopname, string orderid, int cityid)
        {
            string count = "您的订单" + orderid.Substring(orderid.Length - 4 - 1) + "已送到，期待再次与您服务。您的需求，我们极速追求，客服咨询88777077";
            return send(tel, count, 0);
        }

        /// <summary>
        /// 配送员接单后
        /// </summary>
        /// <param name="order"></param>
        /// <param name="deliver"></param>
        /// <returns></returns>
        public static int SendOrderDeliver(string tel, string delivertel, string shopname, string orderid, int cityid)
        {
            string cont = "您在" + shopname + "的订单已被配送员" + delivertel + "取到，正在配送途中。您的需求，我们极速追求，请拨电话88777077";
            return send(tel, cont, 0);
        }

        /// <summary>
        /// 验证码短信
        /// </summary>
        /// <param name="order"></param>
        /// <param name="deliver"></param>
        /// <returns></returns>
        public static int deliver_SendValidCode(string tel, string code)
        {
            string cout = "您的验证码是：" + code + "。请不要把验证码泄露给其他人。";
            return send(tel, cout, 1);
        }

        /// <summary>
        /// 配送员接单后
        /// </summary>
        /// <param name="order"></param>
        /// <param name="deliver"></param>
        /// <returns></returns>
        public static int SendOrderDeliver_city6(string tel, string delivertel, string shopname, string orderid)
        {
            return 1;
            string cont = "您在" + shopname + "的订单已被佳亿配送员" + delivertel + "取到，正在配送途中。同城配送、跑腿，请拨2223000";
            return send(tel, cont, 0);
        }

        /// <summary>
        /// 发送营销短信
        /// </summary>
        /// <param name="mobiles"></param>
        /// <param name="content"></param>
        /// <returns></returns>
        public static int sendADSMS(string mobiles, string content)
        {
            int status = 1;
            string statusMsg = "";

            string sn = CacheUtility.GetSetValue(69);
            string pwd = CacheUtility.GetSetValue(70);

            try
            {
                //string url = "http://10658.cc/webservice/api?method=SendSms&account=" + sn + "&password=" + pwd + "&mobile=" + mobiles+"&content="+ content + "【快先森】&pid=41";

                string url = "http://10658.cc/webservice/api?method=SendSms";
                HttpHelper objhttp = new HttpHelper();
                objhttp.isToLower = false;
                HttpItem objHttpItem = new HttpItem()
                {
                    URL = url,
                    Encoding = "utf-8",
                    Method = "POST",
                    Postdata = "account=" + sn + "&password=" + pwd + "&mobile=" + mobiles + "&content=" + content + "【快先森】&pid=41",
                };
                statusMsg = objhttp.GetHtml(objHttpItem);

            }
            catch (Exception ex)
            {
                status = -1;
                Hangjing.AppLog.AppLog.Error(ex);
                statusMsg = ex.ToString();
            }

            //发送记录
            msgRecordInfo info = new msgRecordInfo();
            info.RanId = 0;
            info.OrderId = "营销短信";
            info.AddDate = DateTime.Now;
            info.Contents = content;
            info.Inve1 = 0;
            info.Inve2 = statusMsg + "  电话号码：" + mobiles;
            info.Inve3 = GetIP();
            info.Inve4 = status.ToString();

            new msgRecord().Add(info);
            return 1;
        }



        /// <summary>
        /// 发送短信,带是否验证次数
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="content">内容</param>
        /// <param name="islimity">0表示不限制次数，1表示要要限制</param>
        /// <returns></returns>
        public static int send(string mobile, string content, int islimity)
        {
            return 0;

            Regex rx = new Regex(@"^[0-9]*$");
            if (rx.IsMatch(mobile) && mobile.Length == 11)
            {

            }
            else
            {
                return 0;
            }

            if ((islimity == 1) && !checkphone(mobile))
            {
                HJlogx.toLog("同一号码，ip一天内发送5次以上：" + mobile);
                return 0;
            }

            int status = 1;
            string statusMsg = "";

            string sn = CacheUtility.GetSetValue(67);
            string pwd = CacheUtility.GetSetValue(68);

            //发送记录
            msgRecordInfo info = new msgRecordInfo();
            info.RanId = 0;
            info.OrderId = mobile;
            info.AddDate = DateTime.Now;
            info.Contents = content;
            info.Inve1 = 0;
            info.Inve2 = statusMsg;
            info.Inve3 = GetIP();
            info.Inve4 = status.ToString();

            try
            {

                Task.Run(() => {
                    string sendurl = "http://106.ihuyi.cn/webservice/sms.php?method=Submit&account=" + sn + "&password=" + pwd + "&mobile=" + mobile + "&content=" + content;
                    statusMsg = RequestUrl(sendurl);
                    info.Inve2 = statusMsg;
                    new msgRecord().Add(info);
                   // Hangjing.AppLog.AppLog.Info(statusMsg);

                });
            }
            catch (Exception ex)
            {
                status = -1;
                Hangjing.AppLog.AppLog.Error(ex);
                statusMsg = ex.ToString();
                info.Inve2 = statusMsg;
                new msgRecord().Add(info);
            }



         
            return 1;
        }


        /// <summary>
        /// 判断当前手机号,ip一天内发的短信。不能操作过10
        /// </summary>
        /// <param name="phone"></param>
        /// <returns>true表示可继续发短信</returns>
        private static bool checkphone(string phone)
        {
            msgRecord dalmsg = new msgRecord();
            bool issend = false;
            DateTime now = DateTime.Now;
            string phonesql = " OrderId = '" + phone + "' and AddDate  between '" + now.AddDays(-1) + "' and '" + now + "'";

            string ip = GetIP();

            string ipsql = " Inve3 = '" + ip + "' and AddDate  between '" + now.AddDays(-1) + "' and '" + now + "'";

            int ipcount = 50;
            int phonecount = 50;
            if (dalmsg.GetCount(phonesql) >= phonecount || dalmsg.GetCount(ipsql) >= ipcount)
            {
                issend = false;
            }
            else
            {
                issend = true;

            }
            return issend;
        }

        /// <summary>
        /// 访问远程端口，返回数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string RequestUrl(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.MaximumAutomaticRedirections = 3;
            request.Timeout = 0x2710;

            string rs = "";

            using (Stream responseStream = ((HttpWebResponse)request.GetResponse()).GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(responseStream))
                {
                    rs = reader.ReadToEnd();
                    reader.Close();
                    responseStream.Close();
                }
            }
            return rs;
        }

        /// <summary>
        /// 获得当前页面客户端的IP
        /// </summary>
        /// <returns>当前页面客户端的IP</returns>
        public static string GetIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }

            if (string.IsNullOrEmpty(result))
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (string.IsNullOrEmpty(result))
            {
                return "127.0.0.1";
            }

            return result;
        }
    }
}
